<template>
  <div id="app" style="overflow: hidden">
    <div class="search" style="margin-bottom: 15px">
      <span>订单名称：</span>
      <el-input v-model="params.orderName" size="small" style="width: 200px"></el-input>
      <el-button size="small" style="color: #FFFFFF;margin-left: 15px" @click="getOrderList" icon="el-icon-search"> 查询</el-button>
      <el-button
          size="small"
          style="
                margin-left: 10px;
                background-color: #303e9d;
                color: #eeeeee;
              "
          @click="_reset"
          icon="el-icon-refresh"
      >重置
      </el-button>
    </div>
    <div class="centerTable">
      <el-table :data="orderList" height="calc(100vh - 250px)"
                border stripe :cell-style="{ 'textAlign': 'center' }"
                :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }">
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="wechatOrderId" label="订单编号"></el-table-column>
        <el-table-column prop="assignName" label="订单名称"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="areaName" label="所属仓库"></el-table-column>
        <el-table-column label="项目负责人">
          <template slot-scope="scope">
            {{ scope.row.placeName + scope.row.placePhone }}
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="材料总价"></el-table-column>
        <el-table-column label="订单类型">
          <template slot-scope="scope">
            <el-button v-if="scope.row.state==1" style="background-color:#e1f3d8;color:#5daf34">报货</el-button>
            <el-button v-if="scope.row.state==2" style="background-color:#c6e2ff;color:#3a8ee6">补货</el-button>
            <el-button v-if="scope.row.state==3" style="background-color:#fde2e2;color:#e57373">售后补发</el-button>
          </template>

        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <div style="display: flex;flex-wrap: wrap;justify-content: space-around;">
              <el-link style="color: #FEA523;width: 60px;margin-bottom: 5px" @click="check(scope.row)" v-if="authorityList.includes(1301)">查看详情</el-link>
              <el-link style="color: #66b1ff;width: 50px;margin-bottom: 5px" @click="submit(scope.row)"
                       v-if="scope.row.outStatus!=1&&authorityList.includes(1302)">提交
              </el-link>
              <!--              <el-link style="color: #66b1ff;width: 50px;margin-bottom: 5px" @click="submit(scope.row)">提交</el-link>-->
              <el-link style="color: red;width: 50px;margin-bottom: 5px" v-if="authorityList.includes(1303)&&scope.row.isPay==0" @click="deleteOrder(scope.row)">删除</el-link>
              <el-link style="width: 50px;margin-bottom: 5px" v-if="authorityList.includes(1304)&&scope.row.outStatus!=0" @click="saveXlsx(scope.row)">导出</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="padding: 20px 0;" align="center" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                     layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
      </el-pagination>
    </div>
    <submit-order style="position: absolute" ref="submitDialog" @addStatus="receiveMessage"></submit-order>
    <material-detail ref="materialDialog"></material-detail>
  </div>
</template>

<script>
import submitOrder from "./componentDialog/submitOrder.vue";
import materialDetail from "./componentDialog/materialDetail.vue";
import quinn from "../../utils/quinn";
import store from "../../store";
import XLSX from "xlsx-js-style";
import Decimal from "decimal.js";
export default {
  name: "userOrder",
  components: {
    submitOrder,
    materialDetail
  },
  meta: {title: "CAD转化订单", icon: "el-icon-edit-outline", sort: 12,authorityList:1300},
  data() {
    return {
      params: {
        orderName: "",
        pageNumber: 1,
        pageSize: 20
      },
      currentPage:1,
      totalCount:0,
      orderList: [],
      authorityList: []
    }
  },
  created() {
    this.getOrderList()
    const {authorityList = []} = quinn.getStorage("userDatav3") || store.state.userData || {};
    this.authorityList = authorityList
  },
  methods: {
    _reset() {
      this.params = this.$options.data.call(this).params
    },
    getOrderList() {
      const params = this.params
      this.$api.wechatGetWechatOrderList(params).then(res => {
        this.orderList = res.data
        this.totalCount=res.total
      })
    },
    submit(row) {
      this.$refs.submitDialog.handleOpen(row)
    },
    receiveMessage(val) {
      if (val == 1) {
        this.getOrderList()
      }
    },
    check(row) {
      this.$refs.materialDialog.handleOpen(row)
    },
    deleteOrder(info) {
      this.$alert(`删除ID为:${info.assignName}报货单?`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            this.$api.wechatDeleteWechatOrderById({ 'wechatOrderId': info.wechatOrderId }).then(res => {
              if(res==1){
                this.$message.success("删除成功！")
                this.getOrderList()
              }
            })
          }
        }
      });
    },
    saveXlsx(info) {
      const wb = XLSX.utils.book_new();
      let data = [
        [info.assignName],
        [`仓库:${info.areaName}`, '', `实付:${info.refundAmount}`, ''],
        [`创建时间:${info.createTime}`, '', `总价:${info.totalPrice}`, ''],
        [`负责人:${info.placeName}${info.placePhone}`, '', `地址:${info.address}`, ''],
        ['材料名称', '数量', '价格', '小计']]
      this.$api.materialsGetWechatOrderMaterialsDetail({orderNo: info.orderNo}).then(res=>{
        res.map(el => {
          el.salePriceTotal = new Decimal(el.outNum).mul(Decimal(el.salePrice)).toNumber();
          data.push([el.materialName, el.outNum, el.salePrice, el.salePriceTotal])
        })
        // data[data.length + 1] = [info.storeName,`实付:${info.totalDisCount}`,`补贴:${info.totalDiffPrice}`,`总价:${info.totalAmount}`];
        const ws = XLSX.utils.aoa_to_sheet(data);
        ws['!cols'] = [
          { wpx: 200 }, // 第一列宽度为250单位
          { wpx: 100 }, // 第二列宽度为300单位
          { wpx: 100 },  // 第三列宽度为350单位
          { wpx: 100 },
          { wpx: 100 },
          { wpx: 100 }
        ];
        ws["A1"].s = {
          alignment: { horizontal: 'center' },
          font: { blod: true, color: { rgb: '000000' } },
          fill: { fgColor: { rgb: 'ff6a00' } }
        }
        ws["A1"].hpt = 140;
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // 导出工作簿为 Blob 对象
        ws['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 3 } }, { s: { r: 1, c: 0 }, e: { r: 1, c: 1 } }, {
          s: {
            r: 1,
            c: 2
          }, e: { r: 1, c: 3 }
        }, { s: { r: 2, c: 0 }, e: { r: 2, c: 1 } }, { s: { r: 2, c: 2 }, e: { r: 2, c: 3 } }, {
          s: { r: 3, c: 0 },
          e: { r: 3, c: 1 }
        }, { s: { r: 3, c: 2 }, e: { r: 3, c: 3 } }]
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        // 创建一个 Blob 对象
        const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

        // 使用 Blob 对象创建一个链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${info.assignName}${new Date().getTime()}.xlsx`;

        // 触发下载
        link.click();

        // 清理
        URL.revokeObjectURL(link.href);

        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }})
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getOrderList()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getOrderList()
    },
  }
}
</script>

<style scoped>
@import "../../assets/css/public.css";
</style>